package com.lottery.im.module.result.ui.statistics;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import butterknife.BindView;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.GameHistoryInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.module.result.adapter.result.statistics.History115Adapter;
import com.lottery.im.module.result.adapter.result.statistics.HistoryLotteryAdapter;
import com.lottery.im.module.result.adapter.result.statistics.HistoryPkAdapter;
import com.lottery.im.module.result.presenter.WinStatisticsPresenter;
import com.lottery.im.module.result.view.WinStatisticsView;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.rxbus.Subscribe;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 开奖号码
 */
public class WinStatisticsFragment extends BaseSwipeFragment<WinStatisticsPresenter>
    implements WinStatisticsView {
  private final static String GAME_TYPE_KEY = "GAME_TYPE_KEY";

  public static WinStatisticsFragment create(String gameType) {
    WinStatisticsFragment fragment = new WinStatisticsFragment();
    Bundle b = new Bundle();
    b.putString(GAME_TYPE_KEY, gameType);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tabLayout) CommonTabLayout mTabLayout;
  @BindView(R.id.refreshLayout) RefreshLayout mRefreshLayout;
  @BindView(R.id.history_list) RecyclerView mRecyclerView;
  private String[] mTabPkNames = { "号码", "大小", "单双", "冠亚/龙虎" };
  private String[] mTabNames = { "号码", "大小", "单双", "总和/形态" };
  private List<GameHistoryInfo> mHistoryList = new ArrayList<>();
  private HistoryPkAdapter mPkAdapter;
  private History115Adapter m115Adapter;
  private HistoryLotteryAdapter mAdapter;
  private String mGameType = "";
  private int startRow = 0;
  private int pageSize = 30;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_statistics_win;
  }

  @Override protected void initPresenter() {
    presenter = new WinStatisticsPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    if (getArguments() == null) {
      popBackStack();
      return;
    } else {
      RxBus.get().register(this);
      mGameType = getArguments().getString(GAME_TYPE_KEY);
      initTabs();
      mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

      if (Constants.pkArr.contains(mGameType)) {
        mPkAdapter = new HistoryPkAdapter(mHistoryList);
        mRecyclerView.setAdapter(mPkAdapter);
      } else if (Constants.sd115Arr.contains(mGameType)) {
        m115Adapter = new History115Adapter(mHistoryList);
        mRecyclerView.setAdapter(m115Adapter);
      } else {
        mAdapter = new HistoryLotteryAdapter(mHistoryList);
        mRecyclerView.setAdapter(mAdapter);
      }
      RecyclerViewDivider.with(mActivity)
          .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
          .size((int) mActivity.getResources().getDimension(R.dimen.line_size_dp1))
          .hideLastDivider()
          .build()
          .addTo(mRecyclerView);
      mRefreshLayout.setOnRefreshListener(refreshLayout -> {
        refreshLayout.finishRefresh(1000);
        startRow = 0;
        presenter.queryGameTypeResult(mGameType, startRow, pageSize);
      });
      mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
        refreshLayout.finishLoadMore(0);
        startRow += pageSize;
        presenter.queryGameTypeResult(mGameType, startRow, pageSize);
      });
      presenter.queryGameTypeResult(mGameType, startRow, pageSize);
    }
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          if (Constants.pkArr.contains(mGameType)) {
            return mTabPkNames[position];
          } else {
            return mTabNames[position];
          }
        }

        @Override public int getTabSelectedIcon() {
          return 0;
        }

        @Override public int getTabUnselectedIcon() {
          return 0;
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        if (Constants.pkArr.contains(mGameType)) {
          mPkAdapter.setIndex(position);
        } else if (Constants.sd115Arr.contains(mGameType)) {
          m115Adapter.setIndex(position);
        } else {
          mAdapter.setIndex(position);
        }
      }

      @Override public void onTabReselect(int position) {
      }
    });
  }

  @Override public void queryHistorySuccess(List<GameHistoryInfo> list) {
    if (startRow == 0) {
      mHistoryList.clear();
    }
    for (int i = 0; i < list.size(); i++) {
      GameHistoryInfo info = list.get(i);
      String issueId = info.getIssueId();
      String resultDate = info.getResultDate();
      String resultStr = info.getResultStr();
      if (resultDate.length() >= 12) {
        info.setDate(resultDate.substring(8, 10) + ":" + resultDate.substring(10, 12));
      }
      info.setIsSueId(
          issueId.length() >= 3 ? issueId.substring(issueId.length() - 3, issueId.length()) + "期"
              : issueId + "期");
      if (resultStr.length() > 0) {
        String[] str = resultStr.split(",");
        if (Constants.pkArr.contains(mGameType)) {
          if (str.length >= 10) {
            info.setStringStr(Arrays.asList(str));
            int a1 = Integer.parseInt(str[0]);
            int a2 = Integer.parseInt(str[1]);
            int a3 = Integer.parseInt(str[2]);
            int a4 = Integer.parseInt(str[3]);
            int a5 = Integer.parseInt(str[4]);
            int a6 = Integer.parseInt(str[5]);
            int a7 = Integer.parseInt(str[6]);
            int a8 = Integer.parseInt(str[7]);
            int a9 = Integer.parseInt(str[8]);
            int a10 = Integer.parseInt(str[9]);
            int sum = a1 + a2;
            String lh1;
            String lh2;
            String lh3;
            String lh4;
            String lh5;
            String dx;
            String ds;
            if (a1 > a10) {
              lh1 = "龙";
            } else {
              lh1 = "虎";
            }
            if (a2 > a9) {
              lh2 = "龙";
            } else {
              lh2 = "虎";
            }
            if (a3 > a8) {
              lh3 = "龙";
            } else {
              lh3 = "虎";
            }
            if (a4 > a7) {
              lh4 = "龙";
            } else {
              lh4 = "虎";
            }
            if (a5 > a6) {
              lh5 = "龙";
            } else {
              lh5 = "虎";
            }
            if (sum > 11) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            List<String> lhList = new ArrayList<>();
            lhList.add(lh1);
            lhList.add(lh2);
            lhList.add(lh3);
            lhList.add(lh4);
            lhList.add(lh5);
            info.setLhList(lhList);
            info.setHeZhi(sum + "    " + dx + "    " + ds);
          }
        } else if (Constants.sd115Arr.contains(mGameType)) {
          if (str.length >= 5) {
            info.setStringStr(Arrays.asList(str));
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int s = Integer.parseInt(str[3]);
            int g = Integer.parseInt(str[4]);
            int sum = w + q + b + s + g;
            String lh;
            String dx;
            String ds;
            if (w > g) {
              lh = "龙";
            } else if (w < g) {
              lh = "虎";
            } else {
              lh = "和";
            }
            if (sum == 30) {
              dx = "中";
            } else if (sum > 30) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            List<String> lhList = new ArrayList<>();
            lhList.add(sum + "");
            lhList.add(dx);
            lhList.add(ds);
            lhList.add(lh);
            lhList.add(getXingTai(w, q, b));
            lhList.add(getXingTai(q, b, s));
            lhList.add(getXingTai(b, s, g));
            info.setLhList(lhList);
          }
        } else {
          if (str.length >= 5) {
            info.setStringStr(Arrays.asList(str));
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int s = Integer.parseInt(str[3]);
            int g = Integer.parseInt(str[4]);
            int sum = w + q + b + s + g;
            String lh;
            String dx;
            String ds;
            if (w > g) {
              lh = "龙";
            } else if (w < g) {
              lh = "虎";
            } else {
              lh = "和";
            }
            if (sum >= 23) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            List<String> lhList = new ArrayList<>();
            lhList.add(sum + "");
            lhList.add(dx);
            lhList.add(ds);
            lhList.add(lh);
            lhList.add(getXingTai(w, q, b));
            lhList.add(getXingTai(q, b, s));
            lhList.add(getXingTai(b, s, g));
            info.setLhList(lhList);
          }
        }
      }
    }
    mHistoryList.addAll(list);
    if (null != mPkAdapter) {
      mPkAdapter.notifyDataSetChanged();
    }
    if (null != m115Adapter) {
      m115Adapter.notifyDataSetChanged();
    }
    if (null != mAdapter) {
      mAdapter.notifyDataSetChanged();
    }
  }

  private String getXingTai(int a1, int a2, int a3) {
    String xingTai;
    if (a1 == a2 && a2 == a3) {
      xingTai = "豹子";
    } else if (a1 == a2 || a2 == a3 || a1 == a3) {
      xingTai = "对子";
    } else if ((a1 - a2 == 1 && a2 - a3 == 1) || (a3 - a2 == 1 && a2 - a1 == 1) || (a3 - a1 == 1
        && a1 - a2 == 1) || (a1 - a3 == 1 && a3 - a2 == 1) || (a2 - a3 == 1 && a3 - a1 == 1) || (
        a2 - a1 == 1 && a1 - a3 == 1)) {
      xingTai = "顺子";
    } else if (a1 - a2 == 1 || a2 - a3 == 1 || a1 - a3 == 1 || (a2 - a1 == 1 || a3 - a2 == 1
        || a3 - a1 == 1)) {
      xingTai = "半顺";
    } else {
      xingTai = "杂六";
    }
    return xingTai;
  }

  /*
   * 刷新开奖结果结果
   * */
  @Subscribe(code = RxBusCode.REFRESH_CODE)
  public void refresh() {
    if (null == mActivity || mActivity.isFinishing()) {
      return;
    }
    presenter.queryGameTypeResult(mGameType, startRow, pageSize);
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
  }
}
